package omg.SongHandling.DataHandling;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import omg.DbHandling.DatabaseInt;
import omg.Error.DBError;
import omg.Error.NoConnectionError;
import omg.Error.ParserCreationFailedError;
import omg.Error.ParsingFailedError;

public class ParserYouTube extends Parser {

    /**
     * Parser for YouTube URLs.
     * @throws NoConnectionError Raised if no connection to the other URL
     * could be established.
     * @throws ParserCreationFailedError Raised when the Parser doesn't
     * consider itself responsible for the provided URL - to avoid this,
     * check with the static {@link #isResponsibleFor(URL)}.
     * @param uri the you tube url
     */
    public ParserYouTube(URI uri) throws ParserCreationFailedError, NoConnectionError {
            super(uri);
            this.type = "YoutTube";
            if (!ParserYouTube.isResponsibleFor(uri))
                throw new ParserCreationFailedError();
	}
   
    /**
     * Checks whether an URL can be parsed by this Parser realization.
     * @param uri the uniform ressource id pointing to the audio source
     * @return true, if the parse realizations considers itself responsible
     * for the supplied URL, otherwise false
     */
    public static boolean isResponsibleFor(URI uri) {
        try {
            if ("www.youtube.com".equalsIgnoreCase(uri.toURL().getHost()))
                return true;
        } catch (MalformedURLException ex) {} // allowes since return of false gives required signal
        return false;
    }

    @Override
    public String[] parse() throws ParsingFailedError, NoConnectionError {
        try {
            DatabaseInt configuration = omg.DbHandling.DatabaseInt.getInstance();
            File youdlPath = new File(configuration.getConfigValue("youdlLocation"));
            System.out.println("Running youdl: " + youdlPath.toString());
            String[] cmd = {youdlPath.toString(), "-g", this.uri.toURL().toString()};
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String[] videoUrl = {in.readLine()};
            System.out.println(videoUrl[0].toString());
            if (null == videoUrl[0] || !videoUrl[0].startsWith("http://"))
                throw new ParsingFailedError();
            return videoUrl;
        } catch (InterruptedException ex) {
            System.out.println("interrupted");
            throw new ParsingFailedError();
        } catch (IOException ex) {
            System.out.println("IO: " + ex.getMessage() );
            throw new ParsingFailedError();
        } catch (DBError ex) {
            System.out.println("DB");
            throw new ParsingFailedError();
        }
            //        try {
            //            String[] res = Parser.parseFor(Pattern.compile("<param name=\\\\\"movie\\\\\" value=\\\\\"(.+)\\\\\"><param name=\\\\\"flashvars\\\\\" value=\\\\\""), this.uri.toURL().openStream());
            //            if (res.length <= 0)
            //                throw new ParsingFailedError();
            //            res[0] = res[0].trim().replace("\\", "");
            //            return res;
            //        } catch (PatternSyntaxException e) {
            //        }
            //        } catch (IOException e) {
            //            throw new NoConnectionError();
            //        }
    }

    @Override
    public String[][] getMetadata() throws ParsingFailedError, NoConnectionError { // title,artist,album,genre,year
        String[][] metadata = new String[1][5];
        try {
            String[] ret = Parser.parseFor(Pattern.compile("<meta name=\"title\" content=\"(.+)-.+\">"), this.uri.toURL().openStream());
            if (ret.length >= 1)
                metadata[0][1] = ret[0].trim();
            ret = Parser.parseFor(Pattern.compile("<meta name=\"title\" content=\".+-(.+)\">"), this.uri.toURL().openStream());
            if (ret.length >= 1)
                metadata[0][0] = ret[0].trim();
        } catch (PatternSyntaxException e) {
            throw new ParsingFailedError();
        } catch (IOException e) {
            throw new NoConnectionError();
        }
        return metadata;
    }
}

